package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Override
    public List<Cart> findCart() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.orderByAsc(Cart::getCreateTime);
        List<Cart> cartList = cartMapper.selectList(wrapper);
        return cartList;
    }

    @Override
    public Cart add(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getDishId()!=null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId()!=null,Cart::getSetmealId,cart.getSetmealId());
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        Cart cart1 = cartMapper.selectOne(wrapper);
        if (cart1!=null){
            cart1.setNumber(cart1.getNumber()+1);
            cartMapper.updateById(cart1);
            return cart1;
        }else {
            cart.setUserId(UserHolder.get().getId());
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }
    }

    @Override
    public Cart sub(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getDishId()!=null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId()!=null,Cart::getSetmealId,cart.getSetmealId());
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        Cart cart1 = cartMapper.selectOne(wrapper);
        if (cart1.getNumber()>1){
            cart1.setNumber(cart1.getNumber()-1);
            cartMapper.updateById(cart1);
            return cart1;
        }else {
            cartMapper.deleteById(cart1.getId());
            return null;
        }
    }
}
